import React, {useState} from "react";
import {DeviceEventEmitter, SafeAreaView, ScrollView, Text, View} from "react-native";
import {Button, Input, useTheme} from "@rn-vui/themed";
import {makeStyles} from "@rn-vui/themed";
import ApiService from "../../utils/ApiService";
import TokenStorage from "../../utils/TokenStorage";
import {UserDidSigninedNotification} from "../../base/constants";
import KeyboardHeightView from "../components/KeyboardHeightView.tsx";
import AsyncStorage from "@react-native-async-storage/async-storage";

const useStyles = makeStyles(({colors}) => ({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        paddingBottom: 40
    },
    inner: {
        width: 500
    },
    header: {
        alignItems: 'center',
        marginBottom: 50
    },
    title: {
        fontSize: 32,
        fontWeight: 'bold',
        color: colors?.secondary
    },
    button: {
        marginTop: 20,
        height: 50
    },
    input: {
        color: colors?.secondary,
        height: 40
    },
    inputContainer: {},
}))


const Login = () => {
    const styles = useStyles();
    const {colors} = useTheme().theme;
    const [logining, setLogining] = useState(false);
    const [email, setEmail] = useState<string>("");
    const [password, setPassword] = useState<string>("");
    const [emailErr, setEmailErr] = useState<string>("");
    const [passwordErr, setPasswordErr] = useState<string>("");

    const submit = () => {
        setEmailErr("");
        setPasswordErr("");
        if (!email) {
            setEmailErr("please enter your email");
            return false;
        }
        if (!password) {
            setPasswordErr("please enter your password");
            return false;
        }

        setLogining(true);
        ApiService.post("/pos/login", {
            email,
            password,
            client_name: "pos"
        }).then(response => {
            const {access_token} = response.data;
            TokenStorage.updateToken(access_token).then(() => {
                DeviceEventEmitter.emit(UserDidSigninedNotification);
            });
            AsyncStorage.setItem('email', email);
            AsyncStorage.setItem('password', password);
        }).catch(reason => {
            setPasswordErr(reason.message);
        }).finally(() => {
            setLogining(false);
        });
    };

    React.useEffect(() => {
        AsyncStorage.getItem('email').then(email => {
            if (email) {
                setEmail(email);
            } else {
                setEmail('pilot@noodlebox.ie');
            }
        });

        AsyncStorage.getItem('password').then(password => {
            if (password) {
                setPassword(password);
            }
        });
    }, []);

    return (
        <SafeAreaView style={{flex: 1}}>
            <ScrollView scrollEnabled={false} style={{flex: 1}} contentContainerStyle={styles.container}>
                <View style={styles.inner}>
                    <View style={styles.header}>
                        <Text style={styles.title}>Login</Text>
                    </View>
                    <Input
                        placeholder={'Email'}
                        inputStyle={styles.input}
                        inputContainerStyle={styles.inputContainer}
                        placeholderTextColor={colors.grey3}
                        keyboardType={'email-address'}
                        defaultValue={email}
                        onChangeText={setEmail}
                        errorMessage={emailErr}
                        returnKeyType={'done'}
                    />
                    <Input
                        placeholder={'password'}
                        inputStyle={styles.input}
                        inputContainerStyle={styles.inputContainer}
                        placeholderTextColor={colors.grey3}
                        secureTextEntry={true}
                        defaultValue={password}
                        onChangeText={setPassword}
                        errorMessage={passwordErr}
                        returnKeyType={'done'}
                    />
                    <Button
                        title={"login"}
                        buttonStyle={styles.button}
                        loading={logining}
                        disabled={!password || !email || logining}
                        onPress={submit}
                    />
                </View>
                <KeyboardHeightView/>
            </ScrollView>
        </SafeAreaView>
    );
};

export default Login;
